﻿#if ODIN_INSPECTOR
using Sirenix.OdinInspector;
#endif
using UnityEngine;

/// <summary>
/// 基于MonoBehaviour的单例模板
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class MonoSingleton<T> :
#if ODIN_INSPECTOR
        SerializedMonoBehaviour
#else
        MonoBehaviour
#endif
        where T : MonoSingleton<T>
{
    private static T instance = null;
    private static bool isInitialized = false;
    public static T Instance
    {
        get
        {
            if (instance == null)
            {
                T existInstance = FindObjectOfType<T>();
                if (existInstance == null)
                {
                    string instanceName = typeof(T).Name;
                    GameObject instanceGO = new GameObject(instanceName);

                    instance = instanceGO.AddComponent<T>();
                    //之后会立即执行Awake()
                }
                else
                {
                    if (!isInitialized)
                    {
                        instance = existInstance;
                        DontDestroyOnLoad(existInstance.gameObject);
                        existInstance.AutoInit();
                        isInitialized = true;
                    }
                }
            }
            return instance;
        }
    }

    protected virtual void Awake()
    {
        if (isInitialized)
        {
            if(this != instance) 
                DestroyImmediate(this.gameObject);
            return;
        }
        instance = (T)this;
        DontDestroyOnLoad(this.gameObject);
        AutoInit();
        isInitialized = true;
    }

    protected virtual void AutoInit()
    {

    }

    public virtual void Dispose() { 
    
    }
}
